﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using iOak.Business.Campaigns;
using iOak.Business.Resumes;
using iOak.Core;
using iOak.Domain.Campaigns;
using iOak.Common.Untity;
using iOak.Common;

namespace iOak.Web.ExeclHelper
{
    public static class CSVHelper
    {
        private static readonly CampaignService _campaignService = new CampaignService();
        private static readonly ApplicationService _applicationService = new ApplicationService();
        private static readonly ResumeDetailService _resumeDetailService = new ResumeDetailService();
        private static readonly ResumeService _resumeService = new ResumeService();
        private static readonly ApplicationCandidateService _applicationCandidateService = new ApplicationCandidateService();
        private static readonly PolicyService _policyService = new PolicyService();

        public static List<List<string>> GetCSVData(Guid campaignId,Guid prolicyId)
        {
            List<List<string>> returnList = new List<List<string>>();
            List<string> listHeader = new List<string>();
            listHeader.Add("公司名称");
            var policy = _policyService.Retrieve(prolicyId);
            var listResume = _applicationService.GetListByCSV(campaignId);
            
            foreach (var itemResume in listResume)
            {
                var listData = _resumeDetailService.GetListByCSV(itemResume.ResumeId, policy.ResumeTemplateId);
                if (listResume.IndexOf(itemResume) == 0)
                {
                    listHeader.AddRange(listData.Select(s => s.LabelText));
                }
                var listCsvData = listData.Select(
                    s => (s.ValueString ?? string.Empty).Replace(",", "，"));
                List<string> addItem = new List<string>();
                addItem.Add(itemResume.CompanyName.Replace(",","，"));
                addItem.AddRange(listCsvData);
                addItem.Add(itemResume.PassedCheck);
                addItem.Add(itemResume.Notes);
                returnList.Add(addItem);
            }
            listHeader.Add("审核结果");
            listHeader.Add("评价");

            returnList.Insert(0, listHeader);
            return returnList;
        }

        #region 写入csv
        /// <summary>
        /// 写入csv
        /// </summary>
        /// <param name="filePathName"></param>
        /// <param name="list"></param>
        public static void WriteCSV(Guid campaignId)
        {
            var item = _campaignService.Retrieve(campaignId);
            var fileName = item.Subject.Replace(",", "，");

            // 获取数据
            List<List<string>> list = GetCSVData(campaignId,item.PolicyId);

            // 设定名称
            fileName = string.Format("{0}汇总表{1}", fileName, ".csv");

            // 设定路径
            var filePath = string.Format("{0}files\\ExportImport\\{1}",
                HttpContext.Current.Request.PhysicalApplicationPath, fileName);

            // 存在删除文件
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            StreamWriter fileWriter = new StreamWriter(filePath, false, Encoding.Default);
            foreach (var itemData in list)
            {
                fileWriter.WriteLine(String.Join(",", itemData));
            }
            fileWriter.Flush();
            fileWriter.Close();

            CommonHelper.WriteResponseCSV(filePath, fileName);

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }
        #endregion

        public static void ExportAllCSV()
        {
            List<Campaign> campaignList = _campaignService.FindCampaigns(string.Empty, null, null, null);
            var listAll = new List<List<string>>() { new List<string>() { "名称", "起始日", "截止日", "收到申请数", "符合人数", "候选人数", "状态" } };
            var listData = campaignList.ConvertAll<List<string>>(campaign =>
                {
                    var returnItem = new List<string>();
                    returnItem.Add(campaign.Subject);
                    returnItem.Add(campaign.StartDate.ToShortDateString());
                    returnItem.Add(campaign.EndDate.ToShortDateString());
                    //总申请书个数
                    int applicationCount = _applicationService.GetCountByCampaignId(campaign.CampaignId);
                    //未申报的申请书个数
                    int openCount = _applicationService.GetCountByCampaignId(campaign.CampaignId, ApplicationStatus.Open);

                    // 收到申请数
                    returnItem.Add((applicationCount - openCount).ToString());

                    // 符合人数
                    returnItem.Add(_applicationCandidateService.GetCount(campaignId: campaign.CampaignId, passed: true).ToString());
                    
                    // 候选人数
                    returnItem.Add(_applicationCandidateService.GetCount(campaign.CampaignId, includeOpen: false).ToString());

                    // 状态
                    returnItem.Add(ResourceHelper.GetCampaignStatusName(campaign.Status));
                    return returnItem;
                });

            listAll.AddRange(listData);

            // 设定名称
            var fileName = string.Format("{0}汇总表{1}", "", ".csv");

            // 设定路径
            var filePath = string.Format("{0}files\\ExportImport\\{1}",
                HttpContext.Current.Request.PhysicalApplicationPath, fileName);

            // 存在删除文件
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            StreamWriter fileWriter = new StreamWriter(filePath, false, Encoding.Default);
            foreach (var itemData in listAll)
            {
                fileWriter.WriteLine(String.Join(",", itemData));
            }
            fileWriter.Flush();
            fileWriter.Close();

            CommonHelper.WriteResponseCSV(filePath, fileName);

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }
    }
}